<template>
  <el-breadcrumb :separator-icon="ArrowRight" style="padding: 8px">
    <el-breadcrumb-item :to="{path: '/products/categories'}"
      >商品列表</el-breadcrumb-item
    >
  </el-breadcrumb>

  <el-form :inline="true" :model="queryParams" class="demo-form-inline">
    <el-form-item label="名字">
      <el-input v-model="queryParams.user" placeholder="请输入名字" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">搜索</el-button>
    </el-form-item>
  </el-form>
  <div style="height: 50px; line-height: 50px">
    <el-button type="primary" @click="editHandle">新增</el-button>
  </div>
  <el-table :data="categoryList" style="width: 100%" border>
    <el-table-column label="序号" align="center" type="index" width="80" />
    <el-table-column prop="name" label="名字" align="center" />
    <el-table-column prop="name" label="分类" align="center">
      <!-- <template #default="scope">
        <span>{{ scope.row.category.name }}</span>
      </template> -->
    </el-table-column>
    <el-table-column prop="name" label="主图" align="center">
      <template #default="scope">
        <el-image
          style="width: 100px; height: 100px"
          :src="scope.row.coverImage"
        />
      </template>
    </el-table-column>

    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="editHandle(scope.row)"
          >修改</el-button
        >
        <el-button type="danger" size="small" @click="delHandle(scope.row)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-dialog
    v-model="dialogVisible"
    :title="itemId ? '修改' : '新增'"
    width="30%"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="70px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="图片" prop="coverImage">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:1337/api/v1/common/upload_file"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img
            v-if="ruleForm.coverImage"
            :src="ruleForm.coverImage"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="简介" prop="desc">
        <el-input v-model="ruleForm.desc" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {ArrowRight} from '@element-plus/icons-vue'
import {getProductsList, getProductCategory} from '../../api/products'
import {ElMessage, ElMessageBox} from 'element-plus'

// 查询条件
const queryParams = reactive({
  user: '',
  region: '',
  per: '10',
  page: '1',
})
const list = ref([]) // tableList
const total = ref(0)
const categoryList = ref([]) // 分类列表
const ruleForm = reactive({
  // 新增和修改的数据
  name: '',
  coverImage: '',
  desc: '',
  content: '',
  views: '',
  price: '',
  category: '',
  onSale: '',
  amount: '',
})
const itemId = ref('')
const ruleFormRef = ref()
const rules = reactive({
  name: [{required: true, message: '请输入名字', trigger: 'blur'}],
  coverImage: [
    {
      required: true,
      message: '请上传图片',
      trigger: 'change',
    },
  ],
  price: [{required: true, message: '请输入价格', trigger: 'blur'}],
  amount: [{required: true, message: '请输入数量', trigger: 'blur'}],
  category: [
    {
      required: true,
      message: '请选择分类',
      trigger: 'change',
    },
  ],
})
const getList = async () => {
  const res = await getProductsList(queryParams)
  console.log(res)
  list.value = res.data
}
getList()
const dialogVisible = ref(false)
const getCategory = async () => {
  const res = await getProductCategory()
  categoryList.value = res.data
}

getCategory()
// 点击新增和修改按钮
const editHandle = (item) => {
  dialogVisible.value = true
  itemId.value = item.id
}

// 搜索确定
const onSubmit = () => {}
// 点击删除
const delHandle = (item) => {
  console.log(item)
  ElMessageBox.confirm('是否要删除?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
// 上传逻辑

const handleAvatarSuccess = (response, uploadFile) => {
  // console.log(URL.createObjectURL(uploadFile.raw!));
  // console.log(uploadFile);
  // console.log(URL.createObjectURL(uploadFile.raw!));

  ruleForm.coverImage = 'http://localhost:1337' + uploadFile.response?.data
  // console.log(form.coverImage);
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (itemId) {
        // alert(111);
        dialogVisible.value = false
        formEl.resetFields()
        itemId.value = ''
      } else {
        // alert(22);
        dialogVisible.value = false
        formEl.resetFields()
      }
    }
  })
}
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
}
</script>
<style scoped></style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
